package com.yuan.kafkastudy.config;

import com.sun.istack.internal.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

@Configuration
public class ThreadExecutorConfig {

    @Bean
    public ThreadPoolExecutor executor() {
        int coreThreadCount = Runtime.getRuntime().availableProcessors()*2;
        int maximumPoolSize = Runtime.getRuntime().availableProcessors()*5;
        ThreadFactory threadFactory = new ThreadFactory() {
            private int count = 0;
            @Override
            public Thread newThread(@NotNull Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("CustomThreadPool-Thread-" + count++);
                count++;
                return thread;
            }
        };
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                coreThreadCount,
                maximumPoolSize,
                60L,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(10000),
                threadFactory,
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        return executor;
    }

}
